//
//  PhotoVideoViewController.m
//  06 美拍相机
//
//  Created by dllo on 16/3/18.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import <AssetsLibrary/AssetsLibrary.h>

//#import <AVFoundation/AVFoundation.h>

#import "PhotoVideoViewController.h"
#import "PhotoVideoFilterCollectionViewCell.h"
#import "NHPlayerView.h"

#import "GPUImage.h"

@interface PhotoVideoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
// 显示特效的CollectionView
@property (strong, nonatomic) IBOutlet UICollectionView *photoVideoFilterCollectionView;

// 保存特效的名称
@property(nonatomic, strong)NSMutableArray *filterNameArr;

// 保存特效
@property(nonatomic, strong)NSMutableArray *filterArr;

// 记录当前点击的特效的位置
@property(nonatomic, assign)NSInteger nowIndex;

// 显示合成的视频的View
@property (strong, nonatomic) IBOutlet UIView *showComposeVideoView;
// 显示合成的进度
@property (strong, nonatomic) IBOutlet UILabel *showComposeProgress;

// 用来控制移动的坐标
@property(nonatomic, assign)NSInteger moveUnit;

// 显示合成之后的视频
@property(nonatomic, retain)NHPlayerView *playerView;

// 判断当前是否为编辑状态
@property(nonatomic, assign)BOOL isEdit;
// 生成的原视频的路径
@property(nonatomic, copy)NSString *moviePath;

// 保存到相册的视频在沙盒中的路径
@property(nonatomic, copy)NSString *saveVideoPath;

// 监控为视频添加滤镜的进程
@property(nonatomic, strong)NSTimer *timer;
// 为视频添加滤镜
@property(nonatomic, strong)GPUImageMovie *movieFile;

// 为视频添加滤镜的时候显示
@property(nonatomic, strong)GPUImageView *filterView;

@end

@implementation PhotoVideoViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if(self.imageArr.count > 0){
        // 合成视频
        [self createVideo];
    }
    else{
        // 将相册中的视频保存到沙盒
        [self videoWithUrl:self.videoURL withFileName:@"video.mov"];
    }
    
    // 修改编辑状态
    self.isEdit = YES;
    // 创建视图
    [self createView];
    
    // 创建数据
    [self createData];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.playerView.frame = CGRectMake(0, 0, self.showComposeVideoView.frame.size.width, self.showComposeVideoView.frame.size.height);
}
#pragma mark 合成视频
- (void)createVideo{
    
    //  合成视频
    [self imageComposeEnlargeVideoImageArr:self.imageArr];
    
}

#pragma mark 创建数据
- (void)createData{
    // 设置初始化的特效为第0个
    self.nowIndex = 0;
    
    self.filterNameArr = [NSMutableArray arrayWithObjects:@"原视频",@"那些年",@"黑与白",@"Poster", nil];
    self.filterArr = [NSMutableArray array];
    // 0 褐色(怀旧)
    GPUImageSepiaFilter *imageSepiaFilter = [[GPUImageSepiaFilter alloc] init];
    [self.filterArr addObject:imageSepiaFilter];
    
    // 1 黑白
    GPUImageGrayscaleFilter *imageGrayscaleFilter = [[GPUImageGrayscaleFilter alloc] init];
    [self.filterArr addObject:imageGrayscaleFilter];
    
    
    // 2 模糊
    GPUImageBoxBlurFilter *imageBoxBlurFilter = [[GPUImageBoxBlurFilter alloc] init];
    [self.filterArr addObject:imageBoxBlurFilter];
    
    
}

#pragma mark 创建视图
- (void)createView{
    
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([PhotoVideoFilterCollectionViewCell class]) bundle:nil];
    [self.photoVideoFilterCollectionView registerNib:nib forCellWithReuseIdentifier:NSStringFromClass([PhotoVideoFilterCollectionViewCell class])];
    
}
#pragma mark CollectionView的协议方法
// 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.filterNameArr.count;
}
// 创建cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    PhotoVideoFilterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([PhotoVideoFilterCollectionViewCell class]) forIndexPath:indexPath];
    
    cell.showFilterImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"2000%ld.png",indexPath.row + 1]];
    cell.showFilterName.text = self.filterNameArr[indexPath.row];
    if(indexPath.row == self.nowIndex){
        cell.showFilterName.textColor = [UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1];
    }
    else{
        cell.showFilterName.textColor = [UIColor grayColor];
    }
    
    return cell;
}
// 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(self.isEdit == NO){
        if(indexPath.row != 0){// 确保点击的不是第一个Cell
            
            // 设置颜色改变
            PhotoVideoFilterCollectionViewCell *cell = (PhotoVideoFilterCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
            cell.showFilterName.textColor = [UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1];
            
            NSIndexPath *previousIndexPath = [NSIndexPath indexPathForItem:self.nowIndex inSection:0];
            PhotoVideoFilterCollectionViewCell *previousCell = (PhotoVideoFilterCollectionViewCell *)[collectionView cellForItemAtIndexPath:previousIndexPath];
            previousCell.showFilterName.textColor = [UIColor grayColor];
            
            self.nowIndex = indexPath.row;
            
            // 添加滤镜
            GPUImageOutput<GPUImageInput> *filter =  (GPUImageOutput<GPUImageInput> *)self.filterArr[indexPath.row - 1];
            
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            NSString *sourcePath = [sandBoxPath stringByAppendingPathComponent:@"video.mov"];
            self.saveVideoPath = [sandBoxPath stringByAppendingPathComponent:@"filterVideo.mov"];
            
            [self addFilterToVideoFilter:filter SourcePath:sourcePath SaveVideoPath:self.saveVideoPath];
            
        }
        else{ // 点击第一个,显示原视频
            // 播放原视频
            self.playerView.playerURLStr = self.moviePath;
            // 设置要保存的视频路径
            self.saveVideoPath = self.moviePath;
            
            // 改变颜色
            PhotoVideoFilterCollectionViewCell *cell = (PhotoVideoFilterCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
            cell.showFilterName.textColor = [UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1];
            
            NSIndexPath *previousIndexPath = [NSIndexPath indexPathForItem:self.nowIndex inSection:0];
            PhotoVideoFilterCollectionViewCell *previousCell = (PhotoVideoFilterCollectionViewCell *)[collectionView cellForItemAtIndexPath:previousIndexPath];
            previousCell.showFilterName.textColor = [UIColor grayColor];
            
            self.nowIndex = indexPath.row;
        }
    }
    else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"正在编辑,请稍后" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // Action
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 添加
        [alert addAction:action];
        // 显示
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
}

#pragma mark UI方法

// 返回按钮的触发方法
- (IBAction)backPreviousView:(id)sender {
    if(self.isEdit == NO){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否保存当前视频到相册" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // Action
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if(self.saveVideoPath ==nil){
                self.saveVideoPath = self.moviePath;
            }
            // 保存视频到相册
            [self saveVideoToAlbumOutputFileURL:[NSURL fileURLWithPath:self.saveVideoPath]];
        }];
        // CancelAction
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // 停止播放
            [self.playerView playerPause];
            // 返回
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
        // 添加
        [alert addAction:cancelAction];
        [alert addAction:action];
        // 显示
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
    else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"正在编辑,退出会丢失当前编辑,是否要退出" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // Action
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:^{
            }];
        }];
        // noAction
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        // 添加
        [alert addAction:noAction];
        [alert addAction:action];
        // 显示
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
}

// 保存视频按钮的触发方法
- (IBAction)SavaVideo:(id)sender {
    if(self.isEdit == NO){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否保存当前视频到相册" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // Action
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if(self.saveVideoPath ==nil){
                self.saveVideoPath = self.moviePath;
            }
            // 保存视频到相册
            [self saveVideoToAlbumOutputFileURL:[NSURL fileURLWithPath:self.saveVideoPath]];
        }];
        // CancelAction
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // 停止播放
            [self.playerView playerPause];
            // 返回
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
        // 添加
        [alert addAction:cancelAction];
        [alert addAction:action];
        // 显示
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
    else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"正在编辑,请稍后" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // Action
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 添加
        [alert addAction:action];
        // 显示
        [self presentViewController:alert animated:YES completion:^{
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark 自定义方法

#pragma mark 将视频从相册写入沙盒

/**
 *  将视频从相册写入沙盒
 *
 *  @param url      视频在相册里的链接
 *  @param fileName 保存在沙盒中的文件的名称
 */
- (void)videoWithUrl:(NSURL *)url withFileName:(NSString *)fileName
{
    // 解析一下,为什么视频不像图片一样一次性开辟本身大小的内存写入?
    // 想想,如果1个视频有1G多,难道直接开辟1G多的空间大小来写?
    
    self.isEdit = YES;
    
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"%@",sandBoxPath);
    NSString * videoPath = [sandBoxPath stringByAppendingPathComponent:fileName];
    self.moviePath = videoPath;
    // 防止重名文件存在
    unlink([videoPath UTF8String]);

    // 提示
    self.showComposeProgress.text = @"正在压缩视频...";
    // 获得主线程
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    // 创建一个并行线程
    dispatch_queue_t queue = dispatch_queue_create("ImportVideo", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
        if (url) {
            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
                ALAssetRepresentation *rep = [asset defaultRepresentation];
                
                char const *cvideoPath = [videoPath UTF8String];
                FILE *file = fopen(cvideoPath, "a+");
                if (file) {
                    const int bufferSize = 1024 * 1024;
                    // 初始化一个1M的buffer
                    Byte *buffer = (Byte*)malloc(bufferSize);
                    NSUInteger read = 0, offset = 0, written = 0;
                    NSError* err = nil;
                    if (rep.size != 0)
                    {
                        do {
                            read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];
                            written = fwrite(buffer, sizeof(char), read, file);
                            offset += read;
                            NSLog(@"成功");
                        } while (read != 0 && !err);//没到结尾，没出错，ok继续
                    }
                    // 释放缓冲区，关闭文件
                    free(buffer);
                    buffer = NULL;
                    fclose(file);
                    file = NULL;
                    dispatch_async(mainQueue, ^{
                        
                        self.showComposeProgress.alpha = 0.0;
                        if(self.playerView == nil){
                            self.playerView = [[NHPlayerView alloc] initWithFrame:CGRectMake(0, 0, self.showComposeVideoView.frame.size.width, self.showComposeVideoView.frame.size.height)];
                            [self.showComposeVideoView addSubview:self.playerView];
                        }
                        self.playerView.playerURLStr = videoPath;
                        
                        self.isEdit = NO;
                    });
                }
                
            } failureBlock:^(NSError *error) {
                
                NSLog(@"%@",error);
                
            }];
        }
    });
    
}

#pragma mark 将图片合成视频
/**
 *  将图片合成视频
 *
 *  @param imageArr 图片数组
 */
- (void)imageComposeEnlargeVideoImageArr:(NSMutableArray *)imageArr{
    NSLog(@"开始合成");

    self.isEdit = YES;
    // 沙盒路径
    NSString *sanBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    
    NSLog(@"%@",sanBoxPath);
    
    // 合成后的视频保存的路径
    self.moviePath = [sanBoxPath stringByAppendingPathComponent:@"video.mov"];
    // 视频的大小
    CGSize movieSize = CGSizeMake(640.0, 480.0);
    
    NSError *error = nil;
    
    // 当前文件是否存在,如果存在就删除掉,重新创建
    unlink([self.moviePath UTF8String]);
    
    // 初始化压缩引擎
    AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:self.moviePath] fileType:AVFileTypeQuickTimeMovie error:&error];
    
    // 断言,就是希望程序在相应位置设定的条件不满足的时候抛出来，用NSParameterAssert让程序crash到相应位置，用来作安全检查
    NSParameterAssert(videoWriter);
    
    if(error){
        NSLog(@"error = %@",[error localizedDescription]);
    }
    // 对生成的视频的设置
    NSDictionary *videoSetting = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecH264,AVVideoCodecKey,[NSNumber numberWithInt:movieSize.width],AVVideoWidthKey,[NSNumber numberWithInt:movieSize.height],AVVideoHeightKey, nil];
    
    AVAssetWriterInput *writerInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSetting];
    NSDictionary *sourcePixelBufferAttributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:kCVPixelFormatType_32ABGR],kCVPixelBufferPixelFormatTypeKey, nil];
    
    AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput  sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary];
    NSParameterAssert(writerInput);
    NSParameterAssert([videoWriter canAddInput:writerInput]);
    
    if([videoWriter canAddInput:writerInput]){
        NSLog(@"1111");
    }
    else{
        NSLog(@"2222");
    }
    
    [videoWriter addInput:writerInput];
    
    [videoWriter startWriting];
    
    [videoWriter startSessionAtSourceTime:kCMTimeZero];
    
    // 将多张图片合成为一个视频文件
    dispatch_queue_t queue = dispatch_queue_create("mediaInputQueue", NULL);
    int __block frame = 0;
    self.showComposeProgress.alpha = 1.0;
    [writerInput requestMediaDataWhenReadyOnQueue:queue usingBlock:^{
        
        
        while ([writerInput isReadyForMoreMediaData]) {
            
            if(++frame >= [imageArr count] * 50){
                
                [writerInput markAsFinished];
                [videoWriter finishWriting];
                
                self.isEdit = NO;
                // 合成结束
                // 隐藏显示进度的Label
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"输出33333333%@" , [NSThread currentThread]);
                    self.showComposeProgress.alpha = 0;
                    // 显示视频
                    if(self.playerView == nil){
                        self.playerView = [[NHPlayerView alloc] initWithFrame:CGRectMake(0, 0, self.showComposeVideoView.frame.size.width, self.showComposeVideoView.frame.size.height)];
                        [self.showComposeVideoView addSubview:self.playerView];
                    }
                    self.playerView.playerURLStr = self.moviePath;
                });
                
                NSLog(@"结束了");
                
#warning 00 在使用了这个方法后,在真机上跑的时候,bloc里面的回调方法不走,因为videoWriter.status 并没有改变,一直是正在写的状态,所以只好使用了上面的[videoWriter finishWriting] 方法
//                [videoWriter finishWritingWithCompletionHandler:^{
//                    NSLog(@"输出22222 %@" , [NSThread currentThread]);
//                    
//                    
//                }];
                
                break;
            }
            
            CVPixelBufferRef buffer = NULL;
            
            int idx = frame / 50 ;
            
            NSLog(@"已完成%0.2f%%",(frame + 1) / (imageArr.count * 50.0) * 100);

            // 刷新进度
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"========%ld" ,  (long)videoWriter.status);
               self.showComposeProgress.text = [NSString stringWithFormat:@"%0.2f%%",(frame) / (imageArr.count * 50.0) * 100];
            });
            
            // 将图片转换为CVPixelBuffer格式
            buffer = (CVPixelBufferRef)[self pixelBufferEnlargFromCGImage:[imageArr[idx] CGImage] size:movieSize];
            
            if(buffer){
                // 把生成的CVPixelBuffer格式合成到一起
                if([adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMake(frame, 10)]){
                    NSLog(@"写入成功");
                    
                    // 设置图片偏移的单位
                    self.moveUnit = frame % 50;
                    CFRelease(buffer);

                }
                else{
                    NSLog(@"写入失败");
                    CFRelease(buffer);
                }
            }
        }
    }];
}
#pragma mark 实现放大效果
- (CVPixelBufferRef)pixelBufferEnlargFromCGImage:(CGImageRef)image size:(CGSize)size {
    
    NSDictionary *options =[NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithBool:YES],kCVPixelBufferCGImageCompatibilityKey,
                            [NSNumber numberWithBool:YES],kCVPixelBufferCGBitmapContextCompatibilityKey,nil];
    CVPixelBufferRef pxbuffer =NULL;
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,size.width,size.height,kCVPixelFormatType_32ARGB,(__bridge CFDictionaryRef _Nullable)(options),&pxbuffer);
    
    NSParameterAssert(status ==kCVReturnSuccess && pxbuffer !=NULL);
    
    CVPixelBufferLockBaseAddress(pxbuffer,0);
    void *pxdata =CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata !=NULL);
    
    CGColorSpaceRef rgbColorSpace=CGColorSpaceCreateDeviceRGB();
    CGContextRef context =CGBitmapContextCreate(pxdata,size.width,size.height,8,4*size.width,rgbColorSpace,kCGImageAlphaPremultipliedFirst);
    NSParameterAssert(context);
    
    
    // 设置视频中的图片的尺寸
    
    CGContextDrawImage(context, CGRectMake(- self.moveUnit * 0.7, - self.moveUnit * 0.7, size.width + self.moveUnit * 1.4, size.height + self.moveUnit * 1.4), image);
    
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    
    CVPixelBufferUnlockBaseAddress(pxbuffer,0);
    
    return pxbuffer;
}
/**
 *  将视频保存到相簿中
 *
 *  @param outputFileURL 视频的地址
 */
- (void)saveVideoToAlbumOutputFileURL:(NSURL *)outputFileURL{
    // 修改编辑状态
    self.isEdit = NO;
    
    // 视频录入完成后在后台将视频存储到相簿
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    
    [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
        if(error){
            NSLog(@"保存视频到相簿过程中发生错误,错误信息%@",error.localizedDescription);
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"保存失败!" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            // Action
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // 返回上一页
                 [self dismissViewControllerAnimated:YES completion:^{
                 }];
            }];
            // 添加
            [alert addAction:action];
            // 显示
            [self presentViewController:alert animated:YES completion:^{
            }];
        }
        else{
            NSLog(@"成功保存视频到相簿.");
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"已保存" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            // Action
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:^{
                }];
            }];
            // 添加
            [alert addAction:action];
            // 显示
            [self presentViewController:alert animated:YES completion:^{
            }];
        }

        // 移除沙盒中的文件
        [[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
    }];
}

#pragma mark 为视频添加滤镜
/**
 *  为视频添加滤镜
 *
 *  @param filter          滤镜
 *  @param sourceVideoPath 源视频保存的位置
 *  @param saveVideoPath   添加滤镜后的视频保存的位置
 */
- (void)addFilterToVideoFilter:(GPUImageOutput<GPUImageInput> *)filter SourcePath:(NSString *)sourceVideoPath SaveVideoPath:(NSString *)saveVideoPath{
    
    // 设置状态值
    self.isEdit = YES;
    
    // 防止重名文件存在
    unlink([saveVideoPath UTF8String]);
    
    self.movieFile = [[GPUImageMovie alloc] initWithURL:[NSURL fileURLWithPath:sourceVideoPath]];
    self.movieFile.runBenchmark = YES;
    self.movieFile.playAtActualSpeed = NO;
    // 添加滤镜
    [self.movieFile addTarget:filter];
    
    // 创建显示视图
    self.filterView = [[GPUImageView alloc] initWithFrame:CGRectMake(0, 0, self.showComposeVideoView.frame.size.width, self.showComposeVideoView.frame.size.height)];
    [self.showComposeVideoView addSubview:self.filterView];
    [filter addTarget:self.filterView];
    
    // 指定输出视频的位置和尺寸self.
    GPUImageMovieWriter *movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:[NSURL fileURLWithPath:saveVideoPath] size:CGSizeMake(640.0, 480.0)];
    [filter addTarget:movieWriter];
    
    movieWriter.shouldPassthroughAudio = YES;
    self.movieFile.audioEncodingTarget = movieWriter;
    [self.movieFile enableSynchronizedEncodingUsingMovieWriter:movieWriter];
    
    // 开始编辑视频
    [movieWriter startRecording];
    [self.movieFile startProcessing];
    
    self.showComposeProgress.alpha = 1.0;
    self.playerView.alpha = 0.0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(updateFilterProgress) userInfo:nil repeats:YES];
    
    // 当编辑结束的时候出发的方法
    [movieWriter setCompletionBlock:^{
        // 移除滤镜,不然会占用大量的内存
        [filter removeTarget:movieWriter];
        [movieWriter finishRecording];
        // 由于使用了上面的两个方法后内存还还在不停的增长,可能是GPUImageMovieWriter中的第278行没解开注释
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.timer invalidate];
            self.showComposeProgress.text = @"100%";
            self.showComposeProgress.alpha = 0.0;
            self.filterView.alpha = 0.0;
            
            // 设置状态值
            self.isEdit = NO;
            
            // 播放视频
            self.playerView = [[NHPlayerView alloc] initWithFrame:CGRectMake(0, 0, self.showComposeVideoView.frame.size.width, self.showComposeVideoView.frame.size.height)];
            [self.showComposeVideoView addSubview:self.playerView];
            self.playerView.playerURLStr = saveVideoPath;
            
        });
        
    }];
}
/**
 *  跟新为视频添加滤镜的进度
 */
- (void)updateFilterProgress{
    self.showComposeProgress.text = [NSString stringWithFormat:@"%d%%",(int)(self.movieFile.progress * 100)];
}


@end
